/**
 * Copyright 2007-2008. Chongqing First Information & Network Co., Ltd. All
 * rights reserved. <a>http://www.cqfirst.com.cn</a>
 */
package com.cqcis.uip.base.framework.filters.adaptor;

import org.apache.mina.common.IoFilterAdapter;
import org.apache.mina.common.IoSession;

import com.cqcis.uip.base.framework.FrameworkConstants;
import com.cqcis.uip.base.framework.common.ControlMsg;
import com.cqcis.uip.base.framework.filters.FilterException;

/**
 * @author huangmy
 * @date   2007-12-3
 */
public abstract class AbstractProtocolWriteFilter extends IoFilterAdapter {		
	@Override
	public void filterWrite(NextFilter nextFilter, IoSession session, WriteRequest writeRequest) throws Exception {
		Object message = writeRequest.getMessage();	
		if (message instanceof ControlMsg || FrameworkConstants.VIRTUAL_TRY_TIMEOUT_BUFFERS.contains(message)) {
			nextFilter.filterWrite(session, writeRequest);
			return;
		}
		
		message = doFilterWrite(message);
		if (message == null) {
			throw new FilterException("Catch Exception in filter, the method of 'filter' can't return null.");
		}  
		
		nextFilter.filterWrite(session, new WriteRequest(message, writeRequest.getFuture(), writeRequest
				.getDestination()));
	}
	
	/**
	 * 处理给定的message, 返回处理后的对象
	 * @param message
	 */
	protected abstract Object doFilterWrite(Object message) throws Exception;	
}
